#!/usr/bin/env python

import sys
import getopt
from pychart import *

from tools import config
config.init () 

from db import mysql

usage="python drawchart -n nodename -p pluginname -s starttime -d deltat -e endtime > out.png"

def main (argv) :
	try :
		opts, args = getopt.getopt(argv, "hp:n:s:d:e:", ["help"])
	except getopt.GetoptError :
		print usage
		sys.exit(2)
	
	node   = "KarnaTest"
	plugin = "loadavg"
	start = 1210000000
	end   = 1220000000
	delta = 30


	for opt,arg in opts :
		if opt in ("-h","--help") :
			print usage
			sys.exit()
		elif opt == "-n" :
			node = arg
		elif opt == "-p" :
			plugin = arg
		elif opt == "-s" :
			start = arg
		elif opt == "-e" :
			end = arg
	
	db = mysql.DBConn ()
	dat = db.query (plugin, node, start, end)
	if len(dat) == 0 :
		sys.exit("No data to plot.")
	num = len (dat[0])
	data = []

	for i in range (1, num) :
		data.append ([])

	y_max = dat[0][1]
	y_min = dat[0][1]

	lasttime = 0

	for d in dat :
		if lasttime == 0 :
			lasttime = d[0]
		for i in range (1, num) :
			if (d[0] - lasttime) > (5 * delta) :
				for j in range (1, int((d[0] - lasttime) / delta)) :
					for k in range (1, num-1) :
						data[i-1].append ([d[0] + j * delta, 0])
			data[i-1].append ([d[0], d[i]])
			if y_max < d[i] :
				y_max = d[i]
			if y_min > d[i] :
				y_min = d[i]
		lasttime = d[0]
	
	delta = (y_max - y_min)/20
	y_min -= delta
	y_max += delta

	xaxis = axis.X(format="/a-60/hL%d", label="date, time [unix time]")
	yaxis = axis.Y(label=plugin)

	theme.output_format="png"

	for i in range(0, len (data)) :
		ar = area.T(size=(400,300), x_axis=xaxis, y_axis=yaxis, \
		x_range = (data[i][0][0],data[i][-1][0]), y_range = (0, y_max))
		#y_min, y_max))
		ar.add_plot (line_plot.T (data = data[i]))
		ar.draw ()

if __name__ == '__main__' :
	main (sys.argv[1:])
